package com.oaklee.tools.code.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

/**
 * 代码自动生成工具
 *
 * @author lee
 * @date 2018-12-07 16:16
 */
public class CodeGenerator {
    private static Properties properties = new Properties();

    static {
        try {
            Resource resource = new FileSystemResource("generator.properties");
            if (!resource.exists()) {
                resource = new ClassPathResource("generator.properties");
            }
            properties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("初始化配置失败");
        }
    }

    /**
     * 读取控制台内容
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {

        boolean useConfig = Boolean.parseBoolean(properties.getProperty("use.config", "false"));

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        gc.setFileOverride(Boolean.parseBoolean(properties.getProperty("file.override", "false")));
        String projectPath = properties.getProperty("project.path", System.getProperty("user.dir"));
        gc.setOutputDir(projectPath + properties.getProperty("output.dir"));
        gc.setAuthor(properties.getProperty("author"));
        gc.setOpen(Boolean.parseBoolean(properties.getProperty("dir.open", "false")));
        // 关闭缓存
        gc.setEnableCache(Boolean.parseBoolean(properties.getProperty("enable.cache", "false")));
        gc.setSwagger2(Boolean.parseBoolean(properties.getProperty("enable.swagger2", "false")));
        gc.setActiveRecord(true);
        gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(properties.getProperty("jdbc.url"));
        dsc.setDriverName(properties.getProperty("jdbc.driver.name"));
        dsc.setUsername(properties.getProperty("jdbc.username"));
        dsc.setPassword(properties.getProperty("jdbc.password"));
        mpg.setDataSource(dsc);

        // 包配置
        final PackageConfig pc = new PackageConfig();
        String moduleName = properties.getProperty("module.name");
        if (!useConfig) {
            moduleName = scanner("模块名");
        }
        pc.setModuleName(moduleName);
        pc.setParent(properties.getProperty("base.module.package"));
        pc.setController(properties.getProperty("base.controller.package"));
        pc.setEntity(properties.getProperty("base.entity.package"));
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + properties.getProperty("output.mapper.dir") + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        String tablePrefixs = properties.getProperty("table.prefixs");
        if (StringUtils.isNotBlank(tablePrefixs)) {
            strategy.setTablePrefix(tablePrefixs.split(","));
        }
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(Boolean.parseBoolean(properties.getProperty("enable.lombok", "false")));
        //如果有则设置 如果没有 注释掉
        strategy.setSuperControllerClass(properties.getProperty("super.controller"));
        strategy.setRestControllerStyle(true);
        //strategy.setSuperServiceClass("");
        //strategy.setSuperServiceImplClass("");
        //表名 可变数组
        String tableNames = properties.getProperty("table.names");
        String[] tables = tableNames.split(",");
        if (!useConfig) {
            tables = scanner("表名(多个用英文逗号间隔)").split(",");
        }
        strategy.setInclude(tables);
        strategy.setLogicDeleteFieldName(properties.getProperty("table.logic.delete.field.name"));
        strategy.setControllerMappingHyphenStyle(Boolean.parseBoolean(properties.getProperty("enable.controller.mapping.hyphen", "false")));
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }


}
